package juc.ProducerAndConsumer;

import java.util.Scanner;

/**
 * @author liweimin
 * @date 2021/4/23 16:26
 * @since
 */
public class WhileAndIfInSynchronizedTest {

    static int control;

    static final Object lock = new Object();

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        new Thread(() -> {
            while (true) {
                synchronized (lock) {
                    while (control != 1) {
                        System.out.println("============线程A wait前============");

                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println("============线程A wait后============");
                    }
                    System.out.println("== 1");
                    lock.notifyAll();
                }
            }
        }, "线程A").start();


        new Thread(() -> {
            while (true) {
                synchronized (lock) {
                    while (control != 2) {
//                    if (control != 2) {
                        System.out.println("============线程B wait前============");

                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println("============线程B wait后============");
                    }
                    System.out.println("== 2");
                    lock.notifyAll();
                }
            }
        }, "线程B").

                start();

        while (true) {
            control = sc.nextInt();
            //输入后唤醒所有线程
            synchronized (lock) {
                lock.notifyAll();
            }
        }

    }
}

